package com.example.filter;

import com.example.untils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Order(-1)  //过滤器执行顺序（值越小，优先级越高）
@Component
public class AuthorizeFilter implements GlobalFilter {
    @Autowired
    private StringRedisTemplate template;

    private static final String PATH="/book";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        Boolean flag = template.hasKey(RedisConstants.LOGIN_USER_KEY);
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        System.out.println("拦截到的地址"+path);
        if(path.contains(PATH)){
            if(flag){
                return chain.filter(exchange);
            }else{
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);  //表示未登陆401
                //拦截请求
                return exchange.getResponse().setComplete();
            }
        }
        //是，放行
        return chain.filter(exchange);
    }
}
